package com.collabscm.waf.domain.repository.support;

import java.util.Map;

import javax.persistence.Query;

import org.springframework.stereotype.Component;

import com.collabscm.waf.domain.repository.QueryFiller;
import com.collabscm.waf.domain.repository.QueryFillerSelector;
import com.collabscm.waf.solution.logging.Logger;
import com.collabscm.waf.solution.logging.LoggerFactory;
import com.collabscm.waf.util.ObjectUtils;
import com.collabscm.waf.vo.QueryParameters;

/**
 * 最为简单的Query填充器
 *
 * @author Zeng Raoxing
 */
@Component
public class SimpleQueryFiller extends QueryFillerSelector.Configuration implements QueryFiller {
	
	private Logger logger = LoggerFactory.getLogger(SimpleQueryFiller.class);
	
	public SimpleQueryFiller() {
		super.addFiller(QueryParameters.class, this);
	}

	/**
	 * 填充查询条件
	 * 
	 * @param query
	 * @param queryParameters
	 */
	@Override 
	public void fill(Query query, QueryParameters queryParameters) {
		if(queryParameters != null) {
			fillFilters(query, queryParameters);
			if(queryParameters.getStart() > 0) {
				query.setFirstResult(queryParameters.getStart());
				query.setMaxResults(queryParameters.getMaxResults());
			}
			if(logger.isTraceEnabled()) {
				logger.trace("调用SimpleQueryFiller.fill： " + ObjectUtils.toString(query) + "设置的查询条件为：" 
						+ ObjectUtils.toString(queryParameters));
			}
		} else {
			logger.warn("调用SimpleQueryFiller.fill，但" + ObjectUtils.toString(query) + "又没有具体的参数。");
		}
	}

	private void fillFilters(Query query, QueryParameters queryParameters) {
		Map<String, Object> filterMap = queryParameters.getFilters();
		for(String name: filterMap.keySet()) {
			query.setParameter(name, filterMap.get(name));
		}
	}

	@Override
	public void fillCountQuery(Query query, QueryParameters parameters) {
		fillFilters(query, parameters);
	}

}
